package com.jf.cloud.live.util;

import cn.hutool.core.io.IoUtil;
import com.jf.cloud.api.biz.feign.AttachFileFeignClient;
import com.jf.cloud.common.exception.LuckException;
import com.jf.cloud.common.response.ServerResponseEntity;
import com.jf.cloud.common.util.ImageUtil;
import com.jf.cloud.common.util.Json;
import com.jf.cloud.live.config.WxConfig;
import com.jf.cloud.live.constant.LiveConstant;
import com.jf.cloud.live.request.WxInterfaceInfo;
import com.jf.cloud.live.response.ImageResponse;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.impl.client.HttpClients;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Objects;

@Component
public class WxImageUtil {
    @Autowired
    private WxInterfaceUtil wxInterfaceUtil;

    @Autowired
    private WxConfig wxConfig;

   @Autowired
   private AttachFileFeignClient attachFileFeignClient;

    @Value("${biz.oss.resources-url}")
    private String imgDomain;

    private static final Logger log = LoggerFactory.getLogger(WxImageUtil.class);

    public String wxImageUpload(String imageUrl) {
        ServerResponseEntity<String> responseEntity= attachFileFeignClient.getfileTypeByfilePath(imageUrl);
        String fileType = responseEntity.getData();
        if(Objects.isNull(fileType)){
            log.error("该直播商品的商品封面图片类型为空");
            throw new LuckException("该直播商品的商品封面图片类型为空");
        }
        if (!imageUrl.contains(LiveConstant.HTTP)) {
            // 给imageUrl 加上文件全路径
            if (Objects.isNull(imgDomain)) {
                // 未配置文件域名，无法上传成功图片
                throw new LuckException("未配置文件域名，无法上传成功图片");
            }
            imageUrl = StringUtils.join(imgDomain,   imageUrl);
        }

        WxInterfaceInfo wxInterfaceInfo = new WxInterfaceInfo();
        try {
            wxInterfaceInfo.setAccessToken(wxConfig.getWxMaService().getAccessToken());
        } catch (WxErrorException e) {
            // 未授权
            throw new LuckException("授权失败，请重新授权");
        }
        wxInterfaceInfo.setBytes(ImageUtil.imgToBinary(imageUrl, fileType));
        return uploadMedia(wxInterfaceInfo, imageUrl, fileType);
    }

    private String uploadMedia(WxInterfaceInfo wxInterfaceInfo, String imageUrl, String fileType) {
        String uploadMediaUrl = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE";
        uploadMediaUrl = uploadMediaUrl.replace("ACCESS_TOKEN", wxInterfaceInfo.getAccessToken()).replace("TYPE", wxInterfaceInfo.getImgType());
        try {
            String fileName = ImageUtil.imgUrlFileName(imageUrl)+"." + fileType;
            HttpPost httpPost = new HttpPost(uploadMediaUrl);
            HttpEntity reqEntity = MultipartEntityBuilder.create()
                    .addPart("media", new ByteArrayBody(wxInterfaceInfo.getBytes(), fileName))
                    .build();

            httpPost.setEntity(reqEntity);
            InputStream content = null;
            InputStreamReader inputStreamReader = null;
            BufferedReader bufferedReader = null;
            try {
                CloseableHttpResponse httpResponse = HttpClients.createDefault().execute(httpPost);
                content = httpResponse.getEntity().getContent();
                // 读取返回流的结果
                inputStreamReader = new InputStreamReader(content, StandardCharsets.UTF_8);
                bufferedReader = new BufferedReader(inputStreamReader);
                StringBuffer buffer = new StringBuffer();
                String str = null;
                while ((str = bufferedReader.readLine()) != null) {
                    buffer.append(str);
                }
                // 使用JSON-lib解析返回结果
                ImageResponse imageResponse = Json.parseObject(buffer.toString(), ImageResponse.class);
                // 测试打印结果
                System.out.println("打印测试结果" + imageResponse);
                if (Objects.isNull(imageResponse)) {
                    throw new LuckException(buffer.toString());
                }
                return imageResponse.getMedia_id();
            } catch (IOException e) {
                log.info("IO异常");
            } finally {
                IoUtil.close(bufferedReader);
                IoUtil.close(inputStreamReader);
                IoUtil.close(content);
            }
        } catch (Exception e) {
            System.out.println("异常");
        }
        return "";
    }

    /**
     * 上传媒体文件
     * @param accessToken 接口访问凭证
     * @param type 媒体文件类型，分别有图片（image）、语音（voice）、视频（video），普通文件(file)
     *   form-data中媒体文件标识，有filename、filelength、content-type等信息
     * @param mediaFileUrl 媒体文件的url
     * 上传的媒体文件限制
     * 图片（image）:1MB，支持JPG格式
     * 语音（voice）：2MB，播放长度不超过60s，支持AMR格式
     * 视频（video）：10MB，支持MP4格式
     * 普通文件（file）：10MB
     * */
    public static String uploadMedia(String accessToken, String type, String mediaFileUrl) {
        WxInterfaceInfo weixinMedia = null;
        // 拼装请求地址
        String uploadMediaUrl = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE";
        uploadMediaUrl = uploadMediaUrl.replace("ACCESS_TOKEN", accessToken).replace("TYPE", type);

        // 定义数据分隔符
        String boundary = "------------7da2e536604c8";
        try {
            URL uploadUrl = new URL(uploadMediaUrl);
            HttpURLConnection uploadConn = (HttpURLConnection) uploadUrl.openConnection();
            uploadConn.setDoOutput(true);
            uploadConn.setDoInput(true);
            uploadConn.setRequestMethod("POST");
            // 设置请求头Content-Type
            uploadConn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
            // 获取媒体文件上传的输出流（往微信服务器写数据）
            OutputStream outputStream = uploadConn.getOutputStream();

            URL mediaUrl = new URL(mediaFileUrl);
            HttpURLConnection meidaConn = (HttpURLConnection) mediaUrl.openConnection();
            meidaConn.setDoOutput(true);
            meidaConn.setRequestMethod("GET");

            // 从请求头中获取内容类型
            String contentType = meidaConn.getHeaderField("Content-Type");
            // 根据内容类型判断文件扩展名
            String fileExt = ImageUtil.imgUrlFileType(mediaFileUrl);
            // 请求体开始
            outputStream.write(("--" + boundary + "\r\n").getBytes());
            outputStream.write(String.format("Content-Disposition: form-data; name=\"media\"; filename=\"file1%s\"\r\n", fileExt).getBytes());
            outputStream.write(String.format("Content-Type: %s\r\n\r\n", contentType).getBytes());

            // 获取媒体文件的输入流（读取文件）
            BufferedInputStream bis = new BufferedInputStream(meidaConn.getInputStream());
            byte[] buf = new byte[8096];
            int size = 0;
            while ((size = bis.read(buf)) != -1) {
                // 将媒体文件写到输出流（往微信服务器写数据）
                outputStream.write(buf, 0, size);
            }
            // 请求体结束
            outputStream.write(("\r\n--" + boundary + "--\r\n").getBytes());
            outputStream.close();
            bis.close();
            meidaConn.disconnect();

            // 获取媒体文件上传的输入流（从微信服务器读数据）
            InputStream inputStream = uploadConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            StringBuffer buffer = new StringBuffer();
            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            // 释放资源
            inputStream.close();
            inputStream = null;
            uploadConn.disconnect();

            // 使用JSON-lib解析返回结果
            ImageResponse imageResponse = Json.parseObject(buffer.toString(), ImageResponse.class);
            // 测试打印结果
            System.out.println("打印测试结果"+imageResponse);
            return imageResponse.getMedia_id();
        } catch (Exception e) {
            weixinMedia = null;
            String error = String.format("上传媒体文件失败：%s", e);
            System.out.println(error);
        }
        return "";
    }
}
